package com.zs.toolbox.web2j.system.core.config.qq;

import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * @author shuai.zhang  on 2018/10/9
 * @description
 */
@Component
@Slf4j
public class QQOAuth {

    RestTemplate restTemplate = new RestTemplate();

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Accessors
    QQMpProperties qqMpProperties;

    static final String
            RequestTokenUrl = "https://graph.qq.com/oauth2.0/token";

    public String getAccessToken(String code, String state) {
        QQRequestTokenEntity qqRequestTokenEntity = new QQRequestTokenEntity()
                .setClient_id(qqMpProperties.getAppId())
                .setRedirect_uri(qqMpProperties.getRedirectUrl())
                .setClient_secret(qqMpProperties.getSecret())
                .setCode(code).setGrant_type("authorization_code");
        String s = restTemplate.postForObject(RequestTokenUrl, qqRequestTokenEntity, String.class);
        return s;
    }

    public String getOpenId(String accessToken) throws QQConnectException {
        return new OpenID(accessToken).getUserOpenID();
    }

    public UserInfoBean getUserInfo(String openId,String accessToken) throws QQConnectException {
        UserInfo qzoneUserInfo = new UserInfo(accessToken, openId);
        UserInfoBean userInfoBean = (UserInfoBean) qzoneUserInfo.getUserInfo();
        return userInfoBean;
    }

}
